module.exports = function (context) {

  return {
    name: 'route-guard-plugin',
    injectHtmlTags() {
      return {
        headTags: [
          // 注入第三方脚本（如果有）
          {
            tagName: 'script',
            attributes: {
              src: 'https://openatom.cn/trivial-services/stats/index/entry?id=10&auto=no',
            },
          },
        ],
        postBodyTags: [
          // 注入初始化逻辑
          {
            tagName: 'script',
            innerHTML: `
              (function() {
                function executeOafsLogic() {
                  if (window && window._oafs) {
                    window._oafs.setDefault({
                      pageId: document.title,
                      userId: '',
                      extra: {
                        path: location.pathname,
                      },
                    });
                    window._oafs.pv();
                  }
                }

                executeOafsLogic();

                // 监听路由变化
                let previousPathname = location.pathname;

                const handleRouteChange = () => {
                  if (location.pathname !== previousPathname) {
                    previousPathname = location.pathname;
                    executeOafsLogic();
                  }
                };

                // 监听 popstate 和 hashchange 事件
                window.addEventListener('popstate', handleRouteChange);
                window.addEventListener('hashchange', handleRouteChange);

                // 兼容 pushState 和 replaceState 的路由变化
                const originalPushState = history.pushState;
                const originalReplaceState = history.replaceState;

                history.pushState = function (...args) {
                  originalPushState.apply(this, args);
                  handleRouteChange();
                };

                history.replaceState = function (...args) {
                  originalReplaceState.apply(this, args);
                  handleRouteChange();
                };

              })();
            `,
          },
        ],
      };
    },
  };
};
